# -*- coding: utf-8 -*-
import base64
import hashlib
import json
import time
import urllib
from collections import OrderedDict

import requests
from django.conf import settings
from pyDes import des, CBC, PAD_PKCS5

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'M201803150010': {  # witch 支付宝wap  2-5000--暂时维护 但先对接
        # 京东wap     10-3000
        # QQwap      10-1000
        # 微信wap     2.0~5000
        # 'password': 'aszx7897891',
        'password': '123123',
        'deskey': 'bj92YfpW',
        'md5key': 'r6f3tSIs',
        'gateway': 'http://way.yf52.com/api/pay?params={}&uname=M201803150010',
        'query_gateway': 'http://way.yf52.com/api/info?params={}&uname=M201803150010',
    },
    'M201804250022': {  # loki 支付宝wap  京东wap QQwap 微信wap
        'password': '123123',
        'deskey': 'Xvs07h9R',
        'md5key': 'JIPOvsvu',
        'gateway': 'http://way.yf52.com/api/pay?params={}&uname=M201804250022',
        'query_gateway': 'http://way.yf52.com/api/info?params={}&uname=M201804250022',
    },
    'M201806080033': {  # dwc 支付宝2.9%（2---3000），京东2.1%（10---3000）
        'password': '123123',
        'deskey': 'UYnIKxqS',
        'md5key': '2RPYUDUd',
        'gateway': 'http://way.yf52.com/api/pay?params={}&uname=M201806080033',
        'query_gateway': 'http://way.yf52.com/api/info?params={}&uname=M201806080033',
    },
    'M201807020041': {  # zs 支付宝2.9%（10---3000），
        'password': '123123',
        'deskey': 'zf01z21r',
        'md5key': 'jyj0610u',
        'gateway': 'http://way.yf52.com/api/pay?params={}&uname=M201807020041',
        'query_gateway': 'http://way.yf52.com/api/info?params={}&uname=M201807020041',
    },
}


def _get_md5_key(mch_id):
    return APP_CONF[mch_id]['md5key']


def _get_des_key(mch_id):
    return APP_CONF[mch_id]['deskey']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_password(mch_id):
    return APP_CONF[mch_id]['password']


def des_encrypt(s, key):
    """
    DES 加密
    :param s: 原始字符串
    :return: 加密后字符串，16进制
    """
    secret_key = key
    iv = secret_key
    k = des(secret_key, CBC, iv, pad=None, padmode=PAD_PKCS5)
    en = k.encrypt(s, padmode=PAD_PKCS5)
    return base64.b64encode(en)


def generate_para_str(d, appid):
    '''  生成下单签名 '''
    s = _get_password(appid) + _get_md5_key(appid)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    return 'p_name={}!p_type={}!p_oid={}!p_money={}!p_url={}!p_remarks={}!p_syspwd={}'.format(
        d['p_name'], d['p_type'], d['p_oid'], d['p_money'], d['p_url'], d['p_remarks'],
        md5key)


def generate_query_para(d, app_id):
    '''  生成查询签名 '''
    s = _get_password(app_id) + _get_md5_key(app_id)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    md5key = m.hexdigest()
    return 'p_name={}!p_oid={}!p_syspwd={}'.format(
        d['p_name'], d['p_oid'], md5key)


def verify_notify_sign(d, app_id):
    sign = d['p_md5']
    s = app_id + d['p_oid'] + d['p_money'] + _get_password(app_id) + _get_md5_key(app_id)
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    calculated_sign = m.hexdigest()
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("beifupay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % d)


# 手机支付宝 (WAY_TYPE_ALIPAY_PHONE)
# 手机微信 (WAY_TYPE_WEBCAT_PHONE)
# 京东钱包 (WAY_TYPE_JD)
# qq WAY_TYPE_QQ_PHONE
# 快捷 WAY_TYPE_BANK_FAST
# 网银h5 WAY_TYPE_BANK_PHONE
def _get_paytype(pay_type):
    if pay_type == 'wxpay':
        return 'WAY_TYPE_WEBCAT_PHONE'
    elif pay_type == 'qq':
        return 'WAY_TYPE_QQ_PHONE'
    elif pay_type == 'alipay':
        return 'WAY_TYPE_ALIPAY_PHONE'
    elif pay_type == 'quick':
        return 'WAY_TYPE_BANK_FAST'
    elif pay_type == 'jd':
        return 'WAY_TYPE_JD'
    else:
        return 'WAY_TYPE_BANK_PHONE'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    service = info['service']
    app_id = info['app_id']
    p_dict = OrderedDict((
        ('p_name', app_id),
        ('p_type', _get_paytype(service)),
        ('p_oid', str(pay.id)),
        ('p_money', str(pay_amount)),
        ('p_bank', ''),
        ('p_url', '{}/pay/api/{}/beifupay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('p_surl', '{}/pay/api/{}/beifupay/{}'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('p_remarks', 'charge'),
        ('p_syspwd', _get_password(app_id)),
        ('uname', app_id),
    ))
    s = generate_para_str(p_dict, app_id)
    us = urllib.quote(s.encode('utf8'))
    d = des_encrypt(us, _get_des_key(app_id))
    if app_id != 'M2018060800344':
        url = _get_gateway(app_id).format(d)
        _LOGGER.info('beifupay create_charge data : %s, %s,%s', s, us, url)
        return {'charge_info': url}
    else:
        data = {'params': d, 'uname': app_id}
        html_text = _build_form(data, _get_gateway(app_id))
        _LOGGER.info('beifupay create_charge data1 : %s', html_text)
        cache_id = redis_cache.save_html(pay.id, html_text)
        return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# success
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    _LOGGER.info("beifupay notify data: %s", data)
    verify_notify_sign(data, app_id)
    pay_id = data['p_oid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('beifupay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = str(data['p_code'])
    mch_id = pay.mch_id
    trade_no = data.get('p_sysid')
    total_fee = float(data['p_money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '1':
        _LOGGER.info('beifupay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    pay_id = pay_order.id
    charge_resp = {}
    p_dict = OrderedDict((
        ('p_name', app_id),
        ('p_oid', str(pay_id)),
        ('p_syspwd', str(int(time.time()))),
        ('uname', app_id),
    ))
    para = generate_query_para(p_dict, app_id)
    us = urllib.quote(para.encode('utf8'))
    d = des_encrypt(us, _get_des_key(app_id))
    url = _get_query_gateway(app_id).format(d)
    _LOGGER.info('beifupay query_charge data : %s, %s', p_dict, url)
    response = requests.get(url)
    _LOGGER.info('beifupay query_charge rsp : %s', response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        trade_status = str(data['p_code'])
        if trade_status == '1':
            trade_no = data.get('p_sysid')
            total_fee = float(data['p_money'])
            extend = {
                'trade_status': trade_status,
                'trade_no': trade_no,
                'total_fee': total_fee
            }
            _LOGGER.info('beifupay query order success, mch_id:%s pay_id:%s',
                         pay_order.mch_id, pay_order.id)
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('beifupay data error, status_code: %s', response.status_code)
